package com.java.admin.news.service;

import com.java.database.entity.News;
import com.java.database.mapper.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class NewsService {

    @Autowired
    private NewsMapper newsMapper;
    String format="yyyy-MM-dd";
    private SimpleDateFormat sdf = new SimpleDateFormat(format);
    private Date date;

    public List<News> query() {

        List<News> newsList = newsMapper.selectAll();
        if (newsList == null) {
            throw new RuntimeException("当前没有新闻");
        }
        return newsList;
    }

    public int insertNews(News news) {

        String currentTime =sdf.format(date);
        news.setNewsbegintime(currentTime);
        news.setStatus(0);

        int insert=newsMapper.insert(news);
        if (insert==0){
            throw new RuntimeException("添加失败");
        }
        return insert;
    }
    public int deleteNews(News news){
        if (news.getNewsid()==null||"".equals(news.getNewsid())){
            throw new RuntimeException("定位新闻失败");
        }

        int deleteByPrimaryKey= newsMapper.deleteByPrimaryKey(news.getNewsid());

        if (deleteByPrimaryKey==0){
            throw new RuntimeException("删除失败");
        }
        return deleteByPrimaryKey;
    }
    public int updateNews(News news){

        int updateByPrimaryKey= newsMapper.updateByPrimaryKey(news);
        if (updateByPrimaryKey==0){
            throw new RuntimeException("更新失败");
        }
        return updateByPrimaryKey;
    }
}
